package com.cgtong.android.fragment;


import android.app.Dialog;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.cgtong.android.R;
import com.cgtong.android.activity.HisProblemsActivity;
import com.cgtong.android.adapter.UserFollowedAdapter;
import com.cgtong.android.base.BaseLazyFragment;
import com.cgtong.android.bean.UserBean;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.UserFollowedContract;
import com.cgtong.android.mvp.presenter.UserFollowedPresenter;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.BaseDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 我关注的人
 * by zhuqingchun
 */
public class UserFollowedFragment extends BaseLazyFragment implements UserFollowedContract.View {


    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.search_bar_fl)
    FrameLayout mSearchBarFl;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout mSwipeLayout;
    @BindView(R.id.search_txt)
    TextView mSearchTxt;
    @BindView(R.id.search_edt)
    EditText mSearchEdt;
    @BindView(R.id.clear_img)
    ImageView mClearImg;
    @BindView(R.id.search_fl)
    FrameLayout mSearchFl;
    private UserFollowedContract.Presenter mPresenter;

    private List<UserBean> mList;
    private BaseQuickAdapter<UserBean, BaseViewHolder> mAdapter;
    private String mSearchKey = "";


    @Override
    public int getLayoutId() {
        return R.layout.fragment_people_followed;
    }

    @Override
    public void initData() {
        mPresenter = new UserFollowedPresenter(this);
        mList = new ArrayList<>();
        initRecyclerView();

        //回车键搜索监听
        mSearchEdt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mSearchEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mSearchKey = mSearchEdt.getText().toString();
                    mPresenter.httpUserFollowedData(0, mSearchKey, true);
                    KeyboardUtils.hideSoftInput(mSearchEdt);
//                    mSearchEdt.setText("");
                    return false;
                }
                return false;
            }
        });
        //显示或隐藏清空按钮
        mSearchEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mClearImg.setVisibility(View.GONE);
                    mSearchKey = "";
//                    loadDataByNet();
                } else {
                    mClearImg.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    /**
     * 初始化列表
     */
    private void initRecyclerView() {
        mSwipeLayout.setColorSchemeResources(R.color.color_scheme);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.httpUserFollowedData(0, mSearchKey, true);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new UserFollowedAdapter(mList);
        mRecyclerView.setAdapter(mAdapter);
//        mRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL));
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                long maxId = mAdapter.getItem(mAdapter.getItemCount() - 2).getId();
                mPresenter.httpUserFollowedData(maxId, mSearchKey, false);


            }
        }, mRecyclerView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HisProblemsActivity.start(getActivity(), mAdapter.getItem(position).getId());

            }
        });
//        mAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
//                showCancelFollowDialog((UserBean) adapter.getItem(position), position);
//                return false;
//            }
//        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                mPresenter.follow(((UserBean) adapter.getItem(position)).getId(), position);
            }
        });
    }

    private void showCancelFollowDialog(final UserBean item, final int position) {
        BaseDialog.create(getChildFragmentManager())
                .setLayoutRes(R.layout.layout_cancel_follow_dialog)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        view.findViewById(R.id.cancel_follow_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.follow(item.getId(), position);
                                dialog.cancel();
                            }
                        });
                        view.findViewById(R.id.cancel_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();

    }


    @Override
    protected void loadDataByNet() {
        mPresenter.httpUserFollowedData(0, mSearchKey, true);
    }

    @Override
    protected void onDataReloadByNet(View v) {
        mSearchKey = "";
        loadDataByNet();

    }


    @Override
    public void setRefreshing(boolean isRefresh) {
        if (mSwipeLayout != null) {
            mSwipeLayout.setRefreshing(isRefresh);
        }
    }

    @Override
    public void setEnableLoadMore(boolean enableLoadMore) {
        mAdapter.setEnableLoadMore(enableLoadMore);
    }

    @Override
    public void onLoadMoreEnd(boolean isLoadMoreEnd) {
        mAdapter.loadMoreEnd(isLoadMoreEnd);
    }


    @Override
    public void onError(ApiException e) {
        PostUtil.postSuccessDelayed(loadService);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_error);
    }


    @Override
    public void onNullData() {
        PostUtil.postSuccessDelayed(loadService);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_empty);
    }

    @Override
    public void onHttpUserFollowedDataSuccess(List<UserBean> datas, boolean isRefresh) {
        PostUtil.postSuccessDelayed(loadService);
        if (isRefresh) {
            mAdapter.setNewData(datas);
        } else {
            mAdapter.addData(datas);
        }
        mAdapter.loadMoreComplete();
    }

    @Override
    public void onFollowSuccess(long id, int position, ApiResult result) {
        EventBus.getDefault().post(mAdapter.getItem(position), ConstantManager.UPDATE_FOLLOWED_USER_STATUS_TAG);
        mAdapter.remove(position);
        if (mAdapter.getItemCount() == 0) {
            mAdapter.setNewData(null);
            mAdapter.setEmptyView(R.layout.layout_empty);
        }
    }

    @OnClick({R.id.clear_img, R.id.search_bar_fl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.clear_img:
                mSearchKey = "";
                mSearchEdt.setText("");
                KeyboardUtils.hideSoftInput(mSearchEdt);
                loadDataByNet();

                break;
            case R.id.search_bar_fl:
                mSearchFl.setVisibility(View.VISIBLE);
                mSearchTxt.setVisibility(View.GONE);
                KeyboardUtils.showSoftInput(mSearchEdt);
                break;
        }
    }
}
